package com.songwo.aspect;

import com.songwo.core.primary.dao.system.LoggerDao;
import com.songwo.core.primary.entity.system.Logger;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Web层的日志切面
 *
 * @author zhongzheng
 */
@Aspect
@Component
@Log4j2
public class WebLogAspect {

    @Pointcut("execution(public * com.songwo.core.web..*.*(..))")
    public void webLog() {
    }

    @Resource
    private LoggerDao loggerDao;

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    Logger logger = new Logger();

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 请求开始时间
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
//        log.info("URL : " + request.getRequestURL().toString());
//        log.info("HTTP_METHOD : " + request.getMethod());
//        log.info("IP : " + request.getRemoteAddr());
//        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

        // 持久化到数据库
        logger.setId(null);
        logger.setUrl(request.getRequestURL().toString());
        logger.setHttpMethod(request.getMethod());
        logger.setIp(request.getRemoteAddr());
        logger.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.setArgs(Arrays.toString(joinPoint.getArgs()));
        logger.setNow(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
//        log.info("RESPONSE : " + ret);
        // 请求总时长
//        log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()) / 1000.000 + "秒");
        logger.setResponse(ret.toString());
        logger.setSpendTime(System.currentTimeMillis() - startTime.get());
        loggerDao.save(logger);
    }
}
